#include "SeqList.h"
void SLInit(SL* ps)
{
	assert(ps);
	ps->arr = (SLDataType*)malloc(sizeof(SLDataType) * INIT_CAPACITY);
	if (ps->arr == NULL)
	{
		perror("malloc");
		return;//错误返回
	}
	ps->size = 0;
	ps->capacity = INIT_CAPACITY;
}

void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	SLInsert(ps, ps->size, x);
}

void SLPopBack(SL* ps)
{
	SLErase(ps, ps->size - 1);
}

//调用一次头插函数,在头部空出一个元素的位置给x插入
void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	SLInsert(ps, 0, x);
}

void SLPrint(SL* ps)
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\n");
}


void SLDestory(SL* ps)
{
	assert(ps);
	if (ps->arr)//arr不为NULL则销毁
	{
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

void SLCheckCapacity(SL* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		SLDataType* tmp = (SLDataType*)realloc(ps->arr, sizeof(SLDataType) * ps->capacity * 2);
		if (tmp == NULL)
		{
			perror("realloc");
			return;//错误返回
		}
		ps->capacity *= 2;
		ps->arr = tmp;
	}
}

void SLPopFront(SL* ps)
{
	SLErase(ps, 0);
}

void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	//pos==0为头插,pos==ps-<size为尾插
	assert(pos >= 0 && pos <= ps->size);
	SLCheckCapacity(ps);
	int end = ps->size - 1;
	while (pos <= end)
	{
		ps->arr[end + 1] = ps->arr[end];
		end--;
	}
	ps->arr[pos] = x;//在a[pos]处插入新元素
	ps->size++;
}

void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(0 <= pos && pos < ps->size);
	int begin = pos + 1;
	while (begin < ps->size)
	{
		ps->arr[begin - 1] = ps->arr[begin];
		begin++;
	}
	ps->size--;
	//ps->size不用单独检查是否为负
	//在assert断言中,已经交代了pos < ps->size,pos不可能为负
}
 int SLFind(SL* ps, SLDataType find)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == find)
			return find;
	}
	//遍历查找
	return -1;//查不到则返回-1
}